package pr.lanmu.config.constant;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 前端Code码
 */
@Getter
@AllArgsConstructor
@Schema(name = "Code", description = "前端Code码")
public class Code {
    public final static Code SUCCESS = new Code(200, "正常");
    public final static Code VALID_PARAM_ERROR_EXCEPTION = new Code(400, "参数有误");
    public final static Code REQUEST_METHOD_ERROR = new Code(400, "请求方式错误");
    public final static Code NO_LOGIN_EXCEPTION = new Code(401, "未登录");
    public final static Code JWT_TOKEN_EXCEPTION = new Code(401, "凭证错误");
    public final static Code JWT_TOKEN_EXPIRED = new Code(401, "凭证失效");
    public final static Code NO_PERMISSION_EXCEPTION = new Code(500, "无权访问");
    public final static Code NOT_FOUND_EXCEPTION = new Code(404, "路径错误");
    public final static Code MAX_UPLOAD_SIZE_EXCEPTION = new Code(501, "文件上传过大");
    public final static Code RUN_ERROR_EXCEPTION = new Code(500, "服务异常");
    public final static Code NOT_MISMATCH_EXCEPTION = new Code(404, "低代码路径定义错误，以请求类型结尾");
    public static List<Code> codes = new ArrayList<>();

    static {
        //获取所有的Code
        Arrays.stream(Code.class.getDeclaredFields())
                .filter(e -> e.getType()
                        .equals(Code.class))
                .forEach(e -> {
                    try {
                        codes.add((Code) e.get(null));
                    } catch (IllegalAccessException illegalAccessException) {
                        illegalAccessException.printStackTrace();
                    }
                });
    }

    @Schema(description = "业务状态码")
    private final int value;
    @Schema(description = "请求结果描述")
    private final String describe;

    public static RuntimeException getException(Code code) {
        return new RuntimeException(code.value + "-" + code.describe);
    }

    public static Code check(String message) {
        return codes.stream()
                .filter(e -> (e.getValue() + "-" + e.getDescribe()).equals(message))
                .findFirst()
                .orElse(null);
    }
}